package dao

import (
	"database/sql"
	"go_20210605/businessError"
	"go_20210605/model"

	"github.com/pkg/errors"
)

type userDao struct{}

var UserDao = userDao{}

// 查询单条数据示例
func (*userDao) FindById(id int) (u *model.User, err error) {
	sqlStr := "select id, name, age from user where id=?"
	u = new(model.User)
	// 非常重要：确保QueryRow之后调用Scan方法，否则持有的数据库链接不会被释放
	err = MysqlDB.QueryRow(sqlStr, id).Scan(&u.Id, &u.Name, &u.Age)
	if err != nil {
		if err == sql.ErrNoRows {
			err = errors.Wrap(businessError.NOT_FOUND_ERROR, "dao find user err")
		} else {
			err = errors.Wrap(businessError.SYSTEM_ERROR, "dao find user err")
		}
	}
	return u, err
}
